﻿using System;
using System.Collections.Generic;
using System.Text;
using KorTransLib;
using System.ComponentModel;

namespace GoogleEarthHelper
{
    public class Geometry
    {
        public static List<Coordinate> GetCircleCoordinates(Coordinate coord, int num_points, double radius_form)
        {
            double centerlat_form,  centerlong_form;

            DecimalDegreeCoordinate dd = (DecimalDegreeCoordinate)TypeDescriptor.GetConverter(typeof(DecimalDegreeCoordinate)).ConvertFrom(coord);
            centerlat_form = dd.lat;
            centerlong_form = dd.lon;

            double lat1, long1;
            double d_rad;
            double d;
            double delta_pts;
            double radial, lat_rad, dlon_rad, lon_rad;

            double degreeToRadian = Math.PI / 180.0;

            // convert coordinates to radians
            lat1 = centerlat_form * degreeToRadian;
            long1 = centerlong_form * degreeToRadian;

            //Earth measures 
            //Year Name	a (meters) b (meters) 1/f Where Used 
            //1980 International 6,378,137 6,356,752 298.257 Worldwide 
            d = radius_form;
            d_rad = d / 6378137;
            List<Coordinate> ret = new List<Coordinate>();
            // loop through the array and write path linestrings
            for (int i = 0; i <= num_points; i++)
            {
                delta_pts = 360/(double)num_points;
                radial = i * 2 * Math.PI / num_points;

                //This algorithm is limited to distances such that dlon < pi/2
                lat_rad = Math.Asin(Math.Sin(lat1) * Math.Cos(d_rad) + Math.Cos(lat1) * Math.Sin(d_rad) * Math.Cos(radial));
                dlon_rad = Math.Atan2(Math.Sin(radial) * Math.Sin(d_rad) * Math.Cos(lat1), Math.Cos(d_rad) - Math.Sin(lat1) * Math.Sin(lat_rad));
                lon_rad = ((long1 + dlon_rad + Math.PI) % (2 * Math.PI)) - Math.PI;
                ret.Add(new DecimalDegreeCoordinate(lat_rad / degreeToRadian, lon_rad / degreeToRadian));
            }
            return ret;
        }
    }
}